<template>
  <div v-loading="loading">
    <quill-editor v-model="content" :options="editorOption" ref="customQuillEditor"> </quill-editor>
    <button @click="sure">确定</button>
    <input type="file" @change="changeImage" accept="image/*" class="liumingta-upload-file" />
  </div>
</template>

<script>
import { quillEditor } from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
import { uploadImage } from './util/upload';

//自定义编辑器的工作条
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],

  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered' }, { 'list': 'bullet' }],
  [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
  [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction

  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'font': [] }],
  [{ 'align': [] }],
  ['link', 'image', 'video'],
  ['clean']                                         // remove formatting button
];

export default {
  data () {
    return {
      content: "",
      file: null,
      loading: false,
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: {
            container: toolbarOptions,  // 工具栏
            handlers: {
              'image': function (value) {
                if (value) {
                  document.querySelector('.liumingta-upload-file').click()
                } else {
                  this.quill.format('image', false);
                }
              }
            }
          }
        }
      },
    }
  },
  components: {
    quillEditor
  },
  methods: {
    setImageInContent (imgUrl) {
      // 获取富文本组件实例
      let quill = this.$refs.customQuillEditor.quill;
      // 获取光标所在位置
      let length = quill.getSelection().index;
      // 插入图片  res.info为服务器返回的图片地址
      quill.insertEmbed(length, 'image', imgUrl)
      // 调整光标到最后
      quill.setSelection(length + 1)
    },
    async changeImage (e) {
      this.loading = true
      this.file = e.target.files[0]
      console.log(',====file=>', this.file);
      var { path } = await uploadImage(this.file)
      this.setImageInContent(path)
      e.target.value = null
        this.loading = false
    },
    sure () {
      console.log('this.content,=====>', this.content);
      debugger
    }
  }
}
</script>